import { useState, useEffect } from 'react'
import { List, Skeleton, message } from 'antd'
import moment from 'moment'
import { MoreOutlined } from '@ant-design/icons'
import style from './index.module.less'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { formatDate } from '@src/assets/js/tool'
import Calendar from '@src/components/calendar'
import { CourtSchema } from '@src/components/schema/court';
import { awaitWrap } from '@js/tool';
import { getCaseListRequest, getDataRequest, getCourtListRequest } from './ajax'
import { useSelector, useDispatch } from 'react-redux';
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import { addWindow } from '@src/redux/actions/tab'

function renderDescription (item: CaseSchema) {
  const a = item.applicant_name
  const r = item.respondent_name
  const res = []
  if (a) {
    res.push(`申请人：${a}`)
  }
  if (r) {
    res.push(`被申请人：${r}`)
  }
  return res.join(';')
}

async function changeDate (
  id: string,
  date: string,
  setCourtList: (v: CourtSchema[]) => void,
  setLoading: (v: boolean) => void,
  setDay: (v: string) => void
) {
  setDay(date)
  setLoading(true)
  const [e, d] = await awaitWrap(getDataRequest(date, id))
  setLoading(false)
  if (e === null && d !== null) {
    setCourtList(d)
  }
}

async function initCaseList (id: string, setCaseList: (v: CaseSchema[]) => void, setCaseLoading: (v: boolean) => void) {
  setCaseLoading(true)
  const [e, d] = await awaitWrap(getCaseListRequest(id))
  setCaseLoading(false)
  if (e === null && d !== null) {
    setCaseList(d)
  }
}

function getTime (d: number) {
  if (!d) {
    return d
  }
  return moment(d * 1000).format('HH:mm')
}

function formatArbitrator (d: CourtSchema) {
  const list = [d.arbitrator]
  if (d.arbitrator1) {
    list.push(d.arbitrator1)
    list.push(d.arbitrator2)
  }
  return list.join('、')
}

// 格式化数据为两位数
function formatDouble (num: number): string {
  return num < 10 ? `0${num}` : `${num}`
}

async function getCourtList (
  year: number,
  month: number,
  id: string,
  setDateList: (v: string[]) => void
) {
  const m = moment(`${year}-${formatDouble(month + 1)}-01 00:00:00`)
  const begintime = Math.floor(m.valueOf() / 1000)
  m.add(1, 'month')
  m.subtract(1, 'd')
  const e = moment(`${m.format('YYYY-MM-DD')} 23:59:59`)
  const endtime = Math.floor(e.valueOf() / 1000)
  const [err, d] = await awaitWrap(getCourtListRequest(begintime, endtime, id))
  if (err === null && d !== null) {
    setDateList(d)
  }
}

export default function () {
  const [caseList, setCaseList] = useState<CaseSchema[]>([])
  const [caseLoading, setCaseLoading] = useState(false)
  const [day, setDay] = useState(moment().format('YYYY-MM-DD'))
  const [year, setYear] = useState(moment().year())
  const [month, setMonth] = useState(moment().month())
  const [dateList, setDateList] = useState<string[]>([])
  const [courtList, setCourtList] = useState<CourtSchema[]>([])
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const { userInfo } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      userInfo: state.basic.userInfo
    }
  })
  useEffect(() => {
    initCaseList(userInfo.id, setCaseList, setCaseLoading)
  }, [])
  useEffect(() => {
    const m = moment(day)
    setYear(m.year())
    setMonth(m.month())
  }, [day])
  useEffect(() => {
    getCourtList(year, month, userInfo.id, setDateList)
  }, [year, month])
  return (
    <div className={style.container}>{/*  */}
      <div className={style.body}>
        <div className={style['body-left']}>
          <div className={style['body-title-line']}>
            <span className={style['body-title__text']}>我的案件</span>
            <span className={style['body__more-btn']} onClick={() => dispatch(addWindow({ id: 'MyCase', title: '我的案件', componentName: 'MyCase', isHome: false }))}>
              <MoreOutlined rotate={90} />
            </span>
          </div>

          <div>
            <List
              itemLayout='horizontal' dataSource={caseList} pagination={false} loading={caseLoading} renderItem={(item, i) => {
                const caseno = item.caseno_desc || item.case_no || item.acceptno_desc || item.acceptno
                return (
                  <List.Item>
                    <Skeleton avatar title={false} loading={item.loading} active>
                      <List.Item.Meta
                        title={<a onClick={() => dispatch(addWindow({ id: `CaseDetail-${item.id}`, title: `案件详情-${caseno || '无'}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id: item.id, editable: true } }))}>{i + 1}、{caseno}</a>}
                        description={renderDescription(item)}
                      />
                      <span>{formatDate(item.docket_datetime, 'YYYY-MM-DD')}</span>
                    </Skeleton>
                  </List.Item>
                )
              }}
            />
          </div>
        </div>
        <div className={style['body-right']}>
          <Calendar changeHandle={s => changeDate(userInfo.id, s, setCourtList, setLoading, setDay)} tagList={dateList} />
          <div className={style['book-list']}>
            <List
              dataSource={courtList} split={false} loading={loading} renderItem={li => {
                return (
                  <List.Item key={li.id}>
                    <div className={style['book-li']}>
                      <span className={style['book-li__time']}>{getTime(li.begin_datetime)}</span>
                      <span>{li.caseno_desc} 案件在{li.name}{li.hearingroom_remark}{li.use}，办案秘书：{li.operator}，仲裁员：{formatArbitrator(li)}</span>
                    </div>
                  </List.Item>
                )
              }}
            />
          </div>
        </div>
      </div>
    </div>
  )
}